package org.ym.tools.adapter;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import org.ym.tools.DateTimeTool;

import java.io.IOException;
import java.util.Date;

/**
 * @author ym
 */
public class ToTimeJsonAdapter extends TypeAdapter<Date> {
    @Override
    public void write(JsonWriter jsonWriter, Date date) throws IOException {
        jsonWriter.value(DateTimeTool.formatDate(date, DateTimeTool.FORMAT_TIME));
    }

    @Override
    public Date read(JsonReader jsonReader) throws IOException {
        if(jsonReader.peek() == JsonToken.NULL){
            jsonReader.nextNull();
            return null;
        }
        String value = jsonReader.nextString();
        return DateTimeTool.parseDate(value, DateTimeTool.FORMAT_TIME);
    }
}
